package gold.digger;

import gold.utils.InputUtil;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC904 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int totalFruit(int[] tree) {
            int maxCount = 0, i = 0, j = 0;
            Map<Integer, Integer> cur = new LinkedHashMap<>();
            int[] steps = getStep(tree);
            while (j < tree.length) {
                cur.put(tree[j], cur.getOrDefault(tree[j], 0) + 1);
                if (cur.size() > 2) {
                    int step = steps[i];
                    int totalTailCount = cur.get(tree[i]);
                    if (totalTailCount <= step) cur.remove(tree[i]);
                    else cur.put(tree[i], totalTailCount - step);
                    i += step;
                }
                maxCount = Math.max(maxCount, j - i + 1);
                ++j;
            }

            return maxCount;
        }

        public int[] getStep(int[] arr) {
            int[] steps = new int[arr.length];
            int i = 0, j = 0;
            while (i < arr.length) {
                steps[i] = 1;
                j = i + 1;
                while (j < arr.length && arr[j] == arr[i]) steps[j++] = 0;
                steps[i] = j - i;
                i = j;
            }
            return steps;
        }
    }


    public void run() {
        Solution solution = new Solution();
        int[] arr = InputUtil.toIntegerArray("[1,2,3,2,2]");
        System.out.println(solution.totalFruit(arr));
    }

    public static void main(String[] args) throws Exception {
        LC904 an = new LC904();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
